import click
import json
import pandas as pd
from common.database import SessionLocal
from datetime import datetime, time

from app.monitor_doris.models.monitor_doris_http_url import MonitorDorisHttpUrl
from core.logger import logger


class MonitorDorisClick(object):
    def __init__(self):
       self.session = SessionLocal()


    def __del__(self):
        self.session.close()



    def url_info_sync_from_excel(self, file_path):
        """
        从excel同步url信息到数据库
        """
        try:
            url_infos = []
            df = pd.read_excel(file_path, "Sheet1")
            for i in df.index.values:
                row_data = df.loc[i].to_dict()
                row_data["is_use"] = True
                url_infos.append(row_data)

            for url_info in url_infos:
                url_info.pop("update_at", "")
                url_object = MonitorDorisHttpUrl.get_object_info_by_url(self.session, url_info["domain"], url_info["url"], url_info["method"])
                if not url_object:
                    # 如果不存在， 则新增
                    result = MonitorDorisHttpUrl.add(self.session, url_info)
                else:
                    # 如果存在， 则更新
                    url_info["uuid"] = url_object["uuid"]
                    result = MonitorDorisHttpUrl.update(self.session, url_info)
                if not result:
                    logger.error(f"{url_info['url']} add success")
                    return False

                logger.info(f"{url_info['url']} add success")
        except Exception as e:
            logger.exception(e)
            return False

        logger.info("update url info from excel success")
        return True




def main():
    monitor_log_click = MonitorDorisClick()

    file_path = "/root/wsl-code/ops-be/app/monitor_doris/script/url_info.xlsx"
    monitor_log_click.url_info_sync_from_excel(file_path)




if __name__ == "__main__":
    main()
